<script setup>
import { ref, reactive, onMounted } from 'vue';
import { reqCaptchaImage, reqKey, reqWXToken } from '@/api/login';
import { SET_TOKEN } from '@/utils/token';
import { useUserStore } from '@/stores/modules/userStore';
import router from '@/router';
import { useRoute } from 'vue-router';
import { showLoadingToast, closeToast, showFailToast } from 'vant';

const route = useRoute();

const userStore = useUserStore();

// form表单
const ruleFormRef = ref();

const passwordInput = ref();

const captchaInput = ref();

// 用户输入的账号,密码和验证码
// 1763 预约老师号码
// 0127 公共教室预约管理
const loginForm = reactive({
    account: '',
    password: '',
    captcha: ''
});

// 表单输入的规则
const rules = reactive({
    account: [{ required: true, message: '请填写号码', trigger: 'blur' }],
    password: [{ required: true, message: '请填写密码', trigger: 'blur' }],
    captcha: [{ required: true, message: '请填验证码', trigger: 'blur' }]
});

// 验证码图像
const captchaImg = ref();

// 获取验证码图像
const getCaptchaImage = async () => {
    try {
        const response = await reqCaptchaImage();

        const img = captchaImg.value;

        img.src = '';

        /** 这是将验证码图像放到img中
         * 下面这段代码的目的是确保在图片加载完成后及时释放
         * 临时 URL 对象，以提高性能并避免内存泄漏的问题。
         */

        img.addEventListener('load', function () {
            window.URL.revokeObjectURL(img.src);
        });

        img.src = window.URL.createObjectURL(response);
    } catch (e) {
        showFailToast(e.message || e.resultMessage);
    }
};

// 点击登录按钮触发
const loginBtnHanlder = formEl => {
    // 判断表单是否满足规则
    if (!formEl) return;
    formEl.validate(async valid => {
        if (valid) {
            // 表单验证成功
            try {
                await userStore.login(loginForm);
                switch (userStore.userType) {
                    case 'teacher':
                        router.push({ name: 'home-teacher' });
                        break;
                    case 'student':
                        router.push({ name: 'home-student' });
                        break;
                    case 'parent':
                        router.push({ name: 'home-parent' });
                        break;
                }
            } catch (e) {
                loginForm.captcha = '';

                await getCaptchaImage();

                showFailToast({
                    message: e.message || e.resultMessage || '用户名或密码有错',
                    duration: 1000
                });
            }
        } else {
            // 表单验证失败
            return false;
        }
    });
};

const GO_REGISTER_URL = 'https://wx.ssti.net.cn/WebOpenAuth';

const wxLogin = async () => {
    try {
        const isnotWeChatBrowser =
            navigator.userAgent.indexOf('MicroMessenger') == -1;

        let {
            goWhere,
            code,
            reply_info: encryptReplyInfo,
            sign: encryptSign
        } = route.query;
        localStorage.setItem('goWhere', goWhere);
        // 判断当前浏览器是否是微信浏览器
        if (isnotWeChatBrowser) {
            throw new Error('请在微信浏览器中打开');
        }

        // 如果路由的query字段中没有code 并且也没有 reply_info 或者 没有 sign 那么就跳转到去获取code和replayinfo 和 sign字段
        if (isCanNotAccess(code)) {
            if (
                isCanNotAccess(encryptReplyInfo) ||
                isCanNotAccess(encryptSign)
            ) {
                const result = await reqKey();
                if (result.status == 200) {
                    const {
                        data: { appId, applyInfo, sign }
                    } = result;

                    window.location = `${GO_REGISTER_URL}?app_id=${appId}&apply_info=${encodeURIComponent(applyInfo)}&sign=${sign}`;
                } else {
                    throw new Error(result.statusText);
                }
            }
        }

        // 自动登录的前提满足上面的条件（路由参数有code reply_info sign)
        if (route.query.reply_info) {
            const result = await reqWXToken(route.query.reply_info);

            if (result.status == 200) {
                SET_TOKEN(result.data);
                await userStore.login();

                let gwflag = localStorage.getItem('gowhere');
                let detail_type = localStorage.getItem('detail_type');
                let detail_id = localStorage.getItem('detail_id');
                if (gwflag == null) {
                    gwflag = 0;
                }
                switch (userStore.userType) {
                    case 'teacher':
                        if (gwflag == 0) router.push({ name: 'leave-system' });
                        else if (gwflag == 1)
                            router.push({ name: 'reservation-index' });
                        else if (gwflag == 2)
                            router.push({ name: 'public-notice' });
                        else if (detail_type == 'detail_leave')
                            router.push({
                                name: 'leaveDetail',
                                query: { id: detail_id }
                            });
                        else if (detail_type == 'detail_leave2')
                            router.push({
                                name: 'releaseDetail',
                                query: { id: detail_id }
                            });
                        else if (detail_type == 'detail_psychologist') {
                            router.push({
                                name: 'psychologyDetail',
                                query: { id: detail_id }
                            });
                        }
                        break;
                    case 'student':
                        if (gwflag == 0) router.push({ name: 'home-student' });
                        if (gwflag == 1) {
                            window.location =
                                'student/index_syuyue.html?v=2021/12/17';
                        }
                        break;
                    case 'parent':
                        router.push({ name: 'home-parent' });
                        break;
                }
            } else {
                throw new Error(result.statusText);
            }
        }
    } catch (e) {
        closeToast();
        loadingText.value = '登录失败';
        showFailToast(e.message);
    }
};

const isLoad = ref(true);

const loadingText = ref('...正在加载中');

onMounted(async () => {
    if (route.query.type == 'admin') {
        isLoad.value = false;
        await getCaptchaImage();
        return;
    }
    showLoadingToast({
        message: '登录中...',
        forbidClick: true,
        duration: 0
    })
    await wxLogin();
});

const isCanNotAccess = tmp => {
    if (tmp === undefined || isEmpty(tmp) || isNull(tmp)) {
        return true;
    } else {
        return false;
    }
};

const PUBLIC_URL = import.meta.env.VITE_APP_IMAGE_URL;

const backgroundImage = {
    backgroundImage: `url(${PUBLIC_URL}/login-bg.jpg)`
};
</script>

<template>
    <div class="load" v-if="isLoad">{{ loadingText }}</div>
    <div class="container" v-else>
        <header class="header" :style="backgroundImage">
            <img class="header_logo" :src="`${PUBLIC_URL}/logo.png`" alt="logo" />
        </header>
        <section class="login">
            <h2 class="login_heading">欢迎登录易校通!</h2>
            <div class="login_form">
                <el-form
                    label-position="top"
                    :model="loginForm"
                    :rules="rules"
                    ref="ruleFormRef"
                >
                    <el-form-item class="login_form_item" prop="account">
                        <el-input
                            size="large"
                            placeholder="请输入账号"
                            v-model.trim="loginForm.account"
                            @keyup.enter="passwordInput.focus()"
                        />
                    </el-form-item>
                    <el-form-item class="login_form_item" prop="password">
                        <el-input
                            ref="passwordInput"
                            size="large"
                            type="password"
                            placeholder="请输入密码"
                            v-model.trim="loginForm.password"
                            @keyup.enter="captchaInput.focus()"
                        />
                    </el-form-item>
                    <el-form-item class="login_form_item--code" prop="captcha">
                        <el-input
                            ref="captchaInput"
                            size="large"
                            class="input-code"
                            placeholder="请输入验证码"
                            v-model.trim="loginForm.captcha"
                            @keyup.enter="loginBtnHanlder(ruleFormRef)"
                        />
                        <div class="code-wrapper" @click="getCaptchaImage">
                            <img ref="captchaImg" alt="验证码" />
                        </div>
                    </el-form-item>
                    <!-- <div class="wrapper">
                        <el-checkbox label="记住密码" class="remember" />
                        <router-link to="" class="forget">
                            忘记密码?
                        </router-link>
                    </div> -->
                    <el-form-item class="login_form_item">
                        <el-button
                            type="success"
                            size="large"
                            class="login_form_item"
                            style="margin-bottom: 8rem"
                            @click="loginBtnHanlder(ruleFormRef)"
                        >
                            登录
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
        </section>
    </div>
</template>

<style scoped lang="scss">
.load {
    font-size: 18rem;
    color: #333;
    text-align: center;
    margin-top: 20rem;
}
.container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    width: 100vw;
    overflow: hidden;
    background-color: rgb(247, 247, 247);
}

.header {
    height: 250rem;
    background-size: cover;
    background-position: 60%;

    &_logo {
        width: 130rem;
        margin: 10rem;
    }
}

.login {
    display: flex;
    flex-direction: column;
    flex: 1;
    margin-top: -20rem;
    background-color: #fff;
    border-radius: 20px;

    &_heading {
        display: flex;
        align-items: center;
        width: 100%;
        height: 70rem;
        padding-left: 30rem;
        font-size: 20rem;
        font-weight: bold;
        letter-spacing: 4rem;
        margin-bottom: 20rem;
    }

    &_form {
        flex: 1;
        padding: 0 30rem;

        &_item {
            width: 100%;
            margin-bottom: 20px;

            &--code {
                display: flex;

                .input-code {
                    flex: 1;
                }

                .code-wrapper {
                    width: 100rem;
                    height: 40rem;
                    margin-left: 20px;

                    img {
                        width: 100%;
                        height: 100%;
                    }
                }
            }
        }
    }

    // 记住密码 忘记密码
    .wrapper {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 5rem;
        margin-bottom: 30rem;

        :deep(a) {
            font-size: 14rem;
        }
    }

    .attention {
        font-size: 16rem;
    }

    .jumpToParentLogin {
        position: relative;
        color: rgb(18, 18, 176);

        &::after {
            position: absolute;
            top: -5rem;
            left: -5rem;
            right: -5rem;
            bottom: -5rem;
        }
    }
}
</style>
